import urllib2
import urllib
import re
import os
import pprint

class psnWeb:

	def __init__(self):

		hh = urllib2.HTTPHandler()
		hsh = urllib2.HTTPSHandler()
		hh.set_http_debuglevel(0)
		hsh.set_http_debuglevel(0)
		self.RETRY = 10

		self.opener = urllib2.build_opener(hh, hsh)

	####################################################
	# Busca a lista de jogos do site ps3trophies.com   #
	####################################################

	def get_all_game_list(self, ):

		URL = 'http://www.ps3trophies.com/games/all/all'
		#URL = 'http://www.ps3trophies.com/games/retail/all'

		request = urllib2.Request(URL)
		br = self.open_request(request)

		ER_TROPHY_ALL = re.compile('.*<a href="/gamepage.php\?id=(?P<game_id>[^"]*)"><b>(?P<name>[^<]*)</b></a><br>.*(?P<trophy_total>[0-9]*) Trophies</a> - <img src="/tc_images/15_hidden.png">x(?P<hidden>[0-9]*) &nbsp;<img src="/tc_images/15_bronze.png">x(?P<bronze>[0-9]*) &nbsp;<img src="/tc_images/15_silver.png">x(?P<silver>[0-9]*) &nbsp;<img src="/tc_images/15_gold.png">x(?P<gold>[0-9]*) &nbsp;<img src="/tc_images/15_platinum.png">x(?P<platinum>[0-9]*).*')
		#ER_TROPHY_ALL = re.compile('.*<a href="/gamepage.php\?id=.*')

		TROPHY_DICT = {}
		TROPHY_LIST = []
		
		for i in br:
			if ER_TROPHY_ALL.match(i):
				TROPHY_DICT["psn_id"]   = ER_TROPHY_ALL.search(i).group('game_id')
				TROPHY_DICT["game_name"] = ER_TROPHY_ALL.search(i).group('name')

				TROPHY_LIST.append(TROPHY_DICT)
				TROPHY_DICT = {}

		return TROPHY_LIST

	###################################
	# Baixa a imagem de de um jogo    #
	# do site ps3trophies.com         #
	###################################

	def download_game_image(self, GAME):
		if GAME.has_key("pic_url"):
			url = GAME["pic_url"]
		else:
			url = 'http://www.ps3trophies.com/trophyicons/%s/icon.png' %GAME["psn_id"]

		req = urllib2.Request(url)

		file_name = "www/media/game/%s" %GAME["psn_id"]

		if	not os.path.exists(file_name):
			os.mkdir(file_name)

		file_name += "/icon.png"

		if	os.path.exists(file_name):
			return

		f = urllib2.urlopen(req)

		# Open our local file for writing
		local_file = open(file_name, "wb")
		#Write to our local file
		local_file.write(f.read())
		local_file.close()

	###################################
	# Baixa a imagem de de um trofeu  #
	# do site ps3trophies.com         #
	###################################

	def download_trophy_image(self, GAME, TROPHY, j, force):

		if not TROPHY.has_key("pic_url"):
			print "No key pic_url"
			return "hidden.png"


		req = urllib2.Request(TROPHY["pic_url"])

		file_name = "www/media/game/%s/" %GAME
		#img_name = TROPHY["pic_url"].split("/")[-1]
		img_name = "trophy_%d.png" %j

		if	not os.path.exists(file_name):
			os.mkdir(file_name)

		file_name += img_name

		if	os.path.exists(file_name) and force is False:
			return img_name

		try:
			f = urllib2.urlopen(req)
		except urllib2.URLError:
			print "not found " + TROPHY["pic_url"]
			return "Miss"

		# Open our local file for writing
		local_file = open(file_name, "wb")
		#Write to our local file
		local_file.write(f.read())
		local_file.close()
		
		return img_name

	####################################################
	# Busca informacoes especificas de um jogo         #
	# do site ps3trophies.com                          #
	####################################################

	def get_game_info(self, GAME):

		print "Game info: %s" %GAME["psn_id"]

		URL = "http://www.ps3trophies.com/gamepage.php?id=%s" %GAME["psn_id"]

		request = urllib2.Request(URL)
		br = self.open_request(request)

		ER_GAME_PUB = re.compile('[ \t]*(?P<pub>[^<]*)</td></tr><tr class="even"><td><b>Developer</b></td><td>.*')
		ER_GAME_DEV = re.compile('[ \t]*(?P<dev>[^<]*)</td></tr><tr class="odd"><td><b>Genre</b></td><td>.*')
		ER_GAME_GNR = re.compile('[ \t]*(?P<gnr>[^<]*)</td></tr><tr class="even"><td><b>Release Date</b></td><td>.*')
		ER_GAME_RLS = re.compile('[ \t]*(?P<rls>[^<]*)</td></tr></table><center><br><br><h3>Ratings</h3><br>.*')

		for i in br:
			if ER_GAME_PUB.match(i):
				GAME["publisher"] = ER_GAME_PUB.search(i).group('pub')[:-1]

			if ER_GAME_DEV.match(i):
				GAME["developer"] = ER_GAME_DEV.search(i).group('dev')[:-1]

			if ER_GAME_GNR.match(i):
				GAME["genre"] = ER_GAME_GNR.search(i).group('gnr')[:-1]

			if ER_GAME_RLS.match(i):
				GAME["release_date"] = ER_GAME_RLS.search(i).group('rls')
				break

		return GAME


	def get_game_trophy_list_ps3t(self, TROPHY):
		print "Get TROPHY info (ps3trophies) for GAME: |%s|" %TROPHY["psn_id"]
		URL = 'http://www.ps3trophies.com/trophies/%s' %TROPHY["psn_id"]

		request = urllib2.Request(URL)
		br = self.open_request(request)

		ER_GAME_TROPHY_NAME = re.compile('.*<div style="padding-top:.*url((?P<pic_url>[^)]*)).*<b>(?P<trophy_name>[^<]*)</b></a>.*')
		ER_GAME_TROPHY_DETAIL = re.compile('.*<br>(?P<trophy_desc>[^<]*)</td>.*alt="(?P<trophy_type>[^"]*)"></td></tr>.*')

		TROPHY_GAME_LIST = []
		TROPHY_GAME_DICT = {}
				
		for i in br:
			if ER_GAME_TROPHY_NAME.match(i):
				TROPHY_GAME_DICT["pic_url"]   = ER_GAME_TROPHY_NAME.search(i).group('pic_url')[1:]
				TROPHY_GAME_DICT["trophy_name"]= ER_GAME_TROPHY_NAME.search(i).group('trophy_name')

			if ER_GAME_TROPHY_DETAIL.match(i):
				TROPHY_GAME_DICT["trophy_desc"] = ER_GAME_TROPHY_DETAIL.search(i).group('trophy_desc')
				TROPHY_GAME_DICT["trophy_type"] = ER_GAME_TROPHY_DETAIL.search(i).group('trophy_type')

				TROPHY_GAME_LIST.append(TROPHY_GAME_DICT)
				TROPHY_GAME_DICT = {}

	def get_game_trophy_list_ps3trophies(self, GAME):
		URL = 'http://www.ps3trophies.com/trophies/%s' %GAME["psn_id"]

		ER_TROPHY_NAME = re.compile('.*<div style="padding-top: 42px; padding-left: 42px; width:12px; height:12px; background: url./(?P<pic_url>[^)]*).*<a href="/trophy/.*"><b>(?P<name>.*)</b></a>')
		ER_TROPHY_DESC = re.compile('.*<br>(?P<desc>.*)</td><td align="center" width="36px"><img src="/tc_images/.*" title="(?P<type>[^"]*)".*')

	#<div style="padding-top: 42px; padding-left: 42px; width:12px; height:12px; background: url(/trophyicons/309-50-Cent-Blood-On-The-Sand/eed9fa_small.png) no-repeat;"></div>        </div></td><td><a href="/trophy/309-50-Cent-Blood-On-The-Sand/eed9fa"><b>G-Unit</b></a>
	#<br>Complete all missions on any difficulty as a member of G-Unit</td><td align="center" width="36px"><img src="/tc_images/40_silver.png" title="Silver" alt="Silver"></td></tr>   <tr class="odd">   <td width="1%"><div style="width:54px; height:54px; margin-left:auto; margin-right:auto; border:1px solid #ccc; padding:4px; background: #ddd;">

		request = urllib2.Request(URL)
		br = self.open_request(request)

		TROPHY_DICT = {}
		TROPHY_LIST = []
		j = 1

		for i in br:
			if ER_TROPHY_NAME.match(i):
				TROPHY_DICT["name"]    = ER_TROPHY_NAME.search(i).group("name")
				TROPHY_DICT["pic_url"] = "http://www.ps3trophies.com/%s" %(ER_TROPHY_NAME.search(i).group("pic_url"))
				continue

			if ER_TROPHY_DESC.match(i):
				TROPHY_DICT["desc"] = ER_TROPHY_DESC.search(i).group("desc")
				TROPHY_DICT["type"] = ER_TROPHY_DESC.search(i).group("type")

				TROPHY_LIST.append(TROPHY_DICT)
				TROPHY_DICT = {}
				j += 1
		return TROPHY_LIST


	def open_request(self, request, cache=False):
		if cache is True:
			fetch = "HTML_FETCH/%s" %request.get_full_url().replace('/','_')

			if os.path.exists(fetch):
				f = open(fetch, 'r')
				data = f.readlines()
				f.close()
				return data
			else:
				f = open(fetch, 'w')

		request.add_header('Accept-Charset', 'utf-8')

		i = 1
		print "Open URL: %s" %request.get_full_url()
		while 1:
			i += 1
			try:
				br = self.opener.open(request)
			except urllib2.HTTPError:
				print "Error HTTPError"
				if (i <= self.RETRY):
					print "Try: %d" %i
					continue
				else:
					x = sys.exc_info()
					traceback.print_exception(*x)
					raise "HTTPError"
			else:
				break


		data_old = data = br.read()
		info = br.info()  

		try:
			ignore, charset = info['Content-Type'].split('charset=')  
			data.decode(charset).encode('utf-8')  
		except:
			data = data_old

		if cache is True:
			f.write(data)
			f.close()

		return data.split('\n')

	def get_game_trophy_list_allps3t(self, GAME):

		game_name = re.sub('^[0-9]*-', '', GAME["psn_id"])

		PSN_URL = 'http://www.allps3trophies.com/psn-games/%s-trophies.html' %game_name
		RTL_URL = 'http://www.allps3trophies.com/retail-games/%s.html' %game_name
		ok = False

		for url in [ PSN_URL, RTL_URL ]:
			try:
				print url
				request = urllib2.Request(url)
				br = self.open_request(request)
			except urllib2.URLError:
				print "URLError"
				continue
			else:
				ok = True
				break

			for i in br:
				print i,

	def get_user_game_info_ps3card(self, user, game):

		URL="http://ps3trophycard.com/profile/%s/%s" %(user, game)
		request = urllib2.Request(URL)
		br = self.open_request(request)

		ER_TROPHY_PIC  = re.compile('.*<td style="width:6%;text-align:center;"><img src="(?P<pic_url>[^"]*)" border="0" /></td>.*')
		ER_TROPHY_NAME = re.compile('.*<td style="width:88%"><strong>(?P<trophy_name>[^<]*)</strong><br />(?P<trophy_desc>[^<]*)<br /><em>Earned (?P<trophy_date>[^<]*)</em></td>.*')
		ER_TROPHY_TYPE = re.compile('.*<td style="width:6%;text-align:center;"><img src="/images/(?P<trophy_type>[BSGP]).png" border="0" width="32" height="32" />.*')
		ER_TROPHY_ID   = re.compile('.*static/trophy/.*/(?P<trophy_id>[0-9]*).png.*')

		TROPHY_LIST = []
		TROPHY_DICT = {}

		for i in br:
			if ER_TROPHY_PIC.match(i):
				pic_url = ER_TROPHY_PIC.search(i).group('pic_url')
				TROPHY_DICT["pic_url"] = "http://ps3trophycard.com%s" %pic_url
				TROPHY_DICT["id"] = ER_TROPHY_ID.search(pic_url).group('trophy_id')
				continue

			if ER_TROPHY_NAME.match(i):
				TROPHY_DICT["name"] = ER_TROPHY_NAME.search(i).group('trophy_name')
				TROPHY_DICT["desc"] = ER_TROPHY_NAME.search(i).group('trophy_desc')
				TROPHY_DICT["date"] = ER_TROPHY_NAME.search(i).group('trophy_date')
				continue

			if ER_TROPHY_TYPE.match(i):
				type = ER_TROPHY_TYPE.search(i).group('trophy_type')
				if type[0] == 'B':
					type = 'bronze'
				elif type[0] == 'S':
					type = 'silver'
				elif type[0] == 'G':
					type = 'gold'
				elif type[0] == 'P':
					type = 'platinum'

				TROPHY_DICT["type"] = type

				TROPHY_LIST.append(TROPHY_DICT)
				TROPHY_DICT = {}

		return TROPHY_LIST

	def get_user_game_info(self, user, game):

		if re.match('^[0-9]{1,}$', game):
			return self.get_user_game_info_ps3card(user, game)

		values = { 'sortBy' : 'id_asc' ,
		'titleId': game}

		data = urllib.urlencode(values)

		URL="http://profiles.us.playstation.com/playstation/psn/profile/%s/get_ordered_title_details_data" %user

		request = urllib2.Request(URL, data)

		request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)')
		request.add_header('Accept', 'text/javascript, text/html, application/xml, text/xml, */*')
		request.add_header('Accept-Language', 'pt-br,pt;q=0.8,en-us;q=0.5,en;q=0.3')
		request.add_header('Accept-Charset', 'utf-8')
		request.add_header('Keep-Alive', '300')
		request.add_header('Connection', 'keep-alive')
		request.add_header('X-Requested-With', 'XMLHttpRequest')
		request.add_header('X-Prototype-Version', '1.6.1_rc3')
		request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
		request.add_header('Referer', 'http://profiles.us.playstation.com/playstation/psn/profiles/%s/trophies/%s' %(user, game))

		br = self.open_request(request, cache=False)

		ER_TROPHY_NAME =   re.compile('.*<span class="trophyTitleSortField">(?P<trophy_name>.*)</span>.*')
	#	ER_TROPHY_DETAIL = re.compile('.*<span class="subtext">(?P<trophy_detail>.*)</span>.*')
		ER_TROPHY_DETAIL = re.compile('.*<span class="subtext">(?P<trophy_detail>[^<*]*)')
		ER_TROPHY_PICURL = re.compile('.*<img border="0" alt="Earned Trophy" title="Earned Trophy" src="(?P<pic_url>http://.*PNG)"/>.*')
		ER_TROPHY_DATE   = re.compile('.*<span class="dateEarnedSortField" style="display:none">(?P<trophy_date>.*)</span>.*')
		ER_TROPHY_TYPE   = re.compile('.*<span class="trophyTypeSortField" style="display:none">.*')
		ER_TROPHY_TYPE_2 = re.compile(' *[PBSGH].*')

		type = 0

		TROPHY_LIST = []
		TROPHY_DICT = {}
		
		for i in br:
			if ER_TROPHY_NAME.match(i):

				if TROPHY_DICT.has_key("name"):
					TROPHY_LIST.append(TROPHY_DICT)
					TROPHY_DICT = {}
					
				TROPHY_DICT["name"] = ER_TROPHY_NAME.search(i).group('trophy_name')
				continue

			if ER_TROPHY_DETAIL.match(i):
				TROPHY_DICT["desc"] = ER_TROPHY_DETAIL.search(i).group('trophy_detail')
				continue

			if ER_TROPHY_DATE.match(i):
				TROPHY_DICT["date"] = ER_TROPHY_DATE.search(i).group('trophy_date')
				continue

			if ER_TROPHY_PICURL.match(i):
				TROPHY_DICT["pic_url"] = ER_TROPHY_PICURL.search(i).group('pic_url')
				continue

			if ER_TROPHY_TYPE.match(i):
				type = 1
				continue

			if type == 1:
				if ER_TROPHY_TYPE_2.match(i):

					# Se denovo apareceu o tipo do trofeu, quer dizer que eh um novo
					if TROPHY_DICT.has_key("type"):
						TROPHY_LIST.append(TROPHY_DICT)
						TROPHY_DICT = {}

					TROPHY_DICT["type"] = i.replace(' ','')
					type = 0

					# A informacao referente ao tipo do trofeu eh a ultima que aparece
					TROPHY_LIST.append(TROPHY_DICT)
					TROPHY_DICT = {}


		#pprint.pprint(TROPHY_LIST)

		for i in TROPHY_LIST:
			if i.has_key("date"):
				if not i.has_key("pic_url"):
					if i["type"] != "HIDDEN":
						print i
						raise "Cant find pic_url"

		return TROPHY_LIST

	def get_user_info(self, user, debug_offline=False):

		URL = "http://profiles.us.playstation.com/playstation/psn/profiles/%s" %user

		request = urllib2.Request(URL)

		request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)')
		request.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
		request.add_header('Accept-Language', 'pt-br,pt;q=0.8,en-us;q=0.5,en;q=0.3')
		request.add_header('Accept-Charset', 'utf-8')
		request.add_header('Keep-Alive', '300')
		request.add_header('Connection', 'keep-alive')

		br = self.open_request(request, cache=False)

		ER_USER_AVATAR = re.compile('.*<img width="57" height="57" border="0" alt="" src="(?P<user_avatar>.*.png)"/>.*')
		ER_USER_LEVEL  = re.compile('.*<div id="leveltext"> (?P<user_level>[0-9]{1,})</div>.*')
		ER_USER_PERC   = re.compile('    (?P<perc_level>[0-9]{1,})%')
		ER_USER_TOTAL  = re.compile('.*<center>(?P<total>[0-9]{1,})</center>')
		ER_USER_PLAT   = re.compile('.*<div class="text platinum">(?P<plat>[0-9]{1,}) Platinum</div>.*')
		ER_USER_GOLD   = re.compile('.*<div class="text gold">(?P<gold>[0-9]{1,}) Gold</div>.*')
		ER_USER_SILVER = re.compile('.*<div class="text silver">(?P<silver>[0-9]{1,}) Silver</div>.*')
		ER_USER_BRONZE = re.compile('.*<div class="text bronze">(?P<bronze>[0-9]{1,}) Bronze</div>.*')

		USER_DICT = {}

		USER_DICT["psn_id"] = user
		
		for i in br:

			if ER_USER_AVATAR.match(i):
				USER_DICT["pic_url"] = ER_USER_AVATAR.search(i).group('user_avatar')
				continue

			if ER_USER_LEVEL.match(i):
				USER_DICT["level"] = int(ER_USER_LEVEL.search(i).group('user_level'))
				continue

			if ER_USER_PERC.match(i):
				USER_DICT["perc_level"] = int(ER_USER_PERC.search(i).group('perc_level'))
				continue

			if ER_USER_TOTAL.match(i):
				USER_DICT["total"] = int(ER_USER_TOTAL.search(i).group('total'))
				continue

			if ER_USER_PLAT.match(i):
				USER_DICT["platinum"] = int(ER_USER_PLAT.search(i).group('plat'))
				continue

			if ER_USER_GOLD.match(i):
				USER_DICT["gold"] = int(ER_USER_GOLD.search(i).group('gold'))
				continue

			if ER_USER_SILVER.match(i):
				USER_DICT["silver"] = int(ER_USER_SILVER.search(i).group('silver'))
				continue

			if ER_USER_BRONZE.match(i):
				USER_DICT["bronze"] = int(ER_USER_BRONZE.search(i).group('bronze'))
				break

		if debug_offline is not False:
			br.close()

		return USER_DICT

	# Tenta achar um user que tem platina no jogo passado
	def get_platinum_user_game(self, psn_id):
		URL = "http://www.ps3trophies.com/platinum/%s" %psn_id

		print URL

		request = urllib2.Request(URL)
		br = self.open_request(request)

		ER_PLT_CLUB = re.compile('.*Platinum Club</h2><table.*')
		ER_USR_PLT  = re.compile('^/(?P<user_id>[^"]*").*')
		
		user = None

		for i in br:
			if ER_PLT_CLUB.match(i):
				list = i.split('profile')
				for j in list:
					if j.startswith('/'):
						user = ER_USR_PLT.search(j).group('user_id')[:-1]

		if not user:
			return

		URL = "http://www.ps3trophies.com/profile/%s" %user

		request = urllib2.Request(URL)
		br = self.open_request(request)

		ER_USER_PSN_ID = re.compile('.*>(?P<user>[^<]*)</a> <br>\((?P<psn_id>[^)]*)\)</center></td>.*')

		for i in br:
			if ER_USER_PSN_ID.match(i):
				if ER_USER_PSN_ID.search(i).group('user') == user:
					user_id = ER_USER_PSN_ID.search(i).group('psn_id')
					print "PlatUser : |%s| - |%s|" %(user_id, psn_id)
					return user_id

		return

	def get_user_games_list(self, user, debug_offline=False):
		
		URL = "http://profiles.us.playstation.com/playstation/psn/profile/%s/get_ordered_trophies_data" %user

		request = urllib2.Request(URL)

		request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)')
		request.add_header('Accept', 'text/javascript, text/html, application/xml, text/xml, */*')
		request.add_header('Accept-Language', 'pt-br,pt;q=0.8,en-us;q=0.5,en;q=0.3')
		request.add_header('Accept-Charset', 'utf-8')
		request.add_header('Keep-Alive', '300')
		request.add_header('Connection', 'keep-alive')
		request.add_header('X-Requested-With', 'XMLHttpRequest')
		request.add_header('X-Prototype-Version', '1.6.1_rc3')
		request.add_header('Referer', 'http://profiles.us.playstation.com/playstation/psn/profiles/%s' %user) 

		br = self.open_request(request)

		ER_GAME_ID   = re.compile(' {10}<a href="/playstation/psn/profiles/%s/trophies/(?P<game_id>.*)">.*' %user)
		ER_GAME_NAME = re.compile('.*<span class="gameTitleSortField">(?P<game_name>.*)</span>.*')
		ER_GAME_PIC  = re.compile('.*<img border="0" alt="" src="(?P<game_pic>http://.*.np.community.playstation.net/trophy/np/.*.PNG)"/>')
		ER_GAME_PERC = re.compile('.*<span class="gameProgressSortField">(?P<game_perc>[0-9]*)</span>%.*')
		ER_GAME_TOTAL= re.compile('.*<span class="gameTrophyCountSortField">(?P<game_total>[0-9]*).*')
		ER_GAME_TROPH= re.compile(' *(?P<game_trophy>[0-9]{1,})$')

		total = 0

		GAME_LIST = []
		GAME_DICT = {}
				
		for i in br:

			if ER_GAME_NAME.match(i):
				GAME_DICT["name"] = ER_GAME_NAME.search(i).group('game_name')

			if ER_GAME_ID.match(i):

				if len(GAME_DICT) > 0:
					GAME_LIST.append(GAME_DICT)
					GAME_DICT = {}

				GAME_DICT["psn_id"] = ER_GAME_ID.search(i).group('game_id')
				continue

			if ER_GAME_PIC.match(i):
				GAME_DICT["pic_url"] = ER_GAME_PIC.search(i).group('game_pic')
				continue

			if ER_GAME_PERC.match(i):
				GAME_DICT["perc_done"] = ER_GAME_PERC.search(i).group('game_perc')
				continue

			if ER_GAME_TOTAL.match(i):
				GAME_DICT["total"] = ER_GAME_TOTAL.search(i).group('game_total')
				total = 1
				continue

			if total > 0:

				if ER_GAME_TROPH.match(i):

					game_trophy = ER_GAME_TROPH.search(i).group('game_trophy')

					if total is 1:
						GAME_DICT["bronze"] = game_trophy
					elif total is 2:
						GAME_DICT["silver"] = game_trophy
					elif total is 3:
						GAME_DICT["gold"] = game_trophy
					elif total is 4:
						GAME_DICT["platinum"] = game_trophy
						total = 0

					if total is not 0:
						total += 1

		if len(GAME_DICT) > 0:
			GAME_LIST.append(GAME_DICT)

		if debug_offline is not False:
			br.close()

		return GAME_LIST


	def get_games_trophycard(self, user, email):

		# Atualiza o card
		URL = "http://ps3trophycard.com/cardupdate/init/%s/%s" %(user, email)
		request = urllib2.Request(URL)
		br = self.open_request(request)

		# Re-pega a lista de jogos
		URL = "http://ps3trophycard.com/profile/%s" %user
		request = urllib2.Request(URL)

		request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)')
		request.add_header('Accept', 'text/javascript, text/html, application/xml, text/xml, */*')
		request.add_header('Accept-Language', 'pt-br,pt;q=0.8,en-us;q=0.5,en;q=0.3')
		request.add_header('Accept-Charset', 'utf-8')
		request.add_header('Keep-Alive', '300')
		request.add_header('Connection', 'keep-alive')
		request.add_header('X-Requested-With', 'XMLHttpRequest')
		request.add_header('X-Prototype-Version', '1.6.1_rc3')
		request.add_header('Referer', 'http://profiles.us.playstation.com/playstation/psn/profiles/%s' %user) 

		try:
			br = self.open_request(request)
		except:
			print "Cant find ps3trophycard"
			return []

		ER_GAME      = re.compile('.*<a href="/profile/.*/(?P<game_id>[0-9]*)"><strong>(?P<game_name>[^<]*)</a></strong>.*')
		ER_GAME_PLAT = re.compile('.*<img src="/images/platinum.png".*')
		ER_TROPHY    = re.compile('.*<td style="text-align:center">(?P<n>[0-9]*)</td>.*')
		ER_PERC_DONE = re.compile('.*<div style="position:absolute;top:5px;left:1px;;width:136px;text-align:center;font-size:0.9em;font-weight:900;color:#000;">(?P<perc_done>[0-9]*)%</div>.*')

		GAME = {}
		GAME_LIST = []

		for i in br:
			if ER_GAME.match(i):

				if GAME.has_key("name"):
					GAME_LIST.append(GAME)
					GAME = {}

				GAME["name"]    = ER_GAME.search(i).group('game_name')
				GAME["psn_id"] = ER_GAME.search(i).group('game_id')
				GAME["card_id"] = GAME["psn_id"]

				GAME["pic_url"] = "http://ps3trophycard.com/images/gameicon/%s.png" %GAME["psn_id"]
			
				if ER_GAME_PLAT.match(i):
					GAME["platinum"] = 1
				else:
					GAME["platinum"] = 0

				start = 1
				continue

			if ER_TROPHY.match(i):
				if start > 0:
					num = ER_TROPHY.search(i).group('n')

					if start is 1:
						GAME["gold"] = num
					elif start is 2:
						GAME["silver"] = num
					elif start is 3:
						GAME["bronze"] = num
					else:
						if GAME.has_key("name"):
							GAME_LIST.append(GAME)
							GAME = {}
							start = 0

					start += 1
					continue

			if ER_PERC_DONE.match(i):
				if start > 0:
					GAME["perc_done"] = ER_PERC_DONE.match(i).group('perc_done')

		if len(GAME) is not 0:
			if GAME.has_key("name"):
				GAME_LIST.append(GAME)
				GAME = {}

		return GAME_LIST

	def ps3trophycard_get_card_url(self, user):
		# Atualiza o card
		URL = "http://ps3trophycard.com/code/%s" %user
		request = urllib2.Request(URL)
		br = self.open_request(request)

		ER_PIC_URL = re.compile('.*<img id="cardpreview" src="(?P<pic_url>[^"]*)" />.*')


		for i in br:
			if ER_PIC_URL.match(i):
				return ER_PIC_URL.match(i).group('pic_url')

		return 
